package com.tf.six.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tf.six.entity.Cart;
import com.tf.six.entity.Order;
import com.tf.six.entity.OrderItem;
import com.tf.six.mapper.CartMapper;
import com.tf.six.mapper.OrderItemMapper;
import com.tf.six.mapper.OrderMapper;
import com.tf.six.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    @Transactional
    public Order createOrder(Integer userId) {
        // 1. 获取用户购物车
        List<Cart> cartItems = cartMapper.selectList(new QueryWrapper<Cart>().eq("user_id", userId));
        if(cartItems.isEmpty()) throw new RuntimeException("购物车为空");

        // 2. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNo("ORD" + UUID.randomUUID().toString().substring(0, 8).toUpperCase());
        order.setCreateTime(LocalDateTime.now());
        order.setStatus("PENDING");

        // 3. 计算总金额并添加订单项
        BigDecimal total = BigDecimal.ZERO;
        for(Cart cart : cartItems) {
            // 实际项目中应从商品服务获取价格
            BigDecimal price = BigDecimal.valueOf(100);
            BigDecimal itemTotal = price.multiply(BigDecimal.valueOf(cart.getQuantity()));
            total = total.add(itemTotal);

            OrderItem item = new OrderItem();
            item.setOrderId(order.getId());
            item.setProductId(cart.getProductId());
            item.setQuantity(cart.getQuantity());
            item.setPrice(price);
            orderItemMapper.insert(item);
        }
        order.setTotalAmount(total);
        save(order);

        // 4. 清空购物车
        cartMapper.delete(new QueryWrapper<Cart>().eq("user_id", userId));

        return order;
    }

    @Override
    public boolean updateOrderStatus(Integer orderId, String status) {
        Order order = getById(orderId);
        if(order == null) return false;

        // 状态校验（简化版）
        if("PAID".equals(status) && !"PENDING".equals(order.getStatus())) {
            throw new RuntimeException("只有待支付订单才能支付");
        }

        order.setStatus(status);
        return updateById(order);
    }
}